package org.jeecg.modules.kuner.browsebase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.ConsoleColors;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.Strings;
import org.jeecg.modules.kuner.browsebase.entity.KrBrowseBase;
import org.jeecg.modules.kuner.browsebase.mapper.KrBrowseBaseMapper;
import org.jeecg.modules.kuner.browsebase.service.IKrBrowseBaseService;
import org.jeecg.modules.kuner.browsebase.vo.BrowseHisVO;
import org.jeecg.modules.kuner.curriculumvitaebase.entity.KrCurriculumVitaeBase;
import org.jeecg.modules.kuner.curriculumvitaebase.service.IKrCurriculumVitaeBaseService;
import org.jeecg.modules.kuner.hirebase.entity.KrHireBase;
import org.jeecg.modules.kuner.hirebase.service.IKrHireBaseService;
import org.jeecg.modules.kuner.useruimestatement.service.IKrUserTimeStatementService;
import org.jeecg.modules.kuner.vipgoodbase.service.IKrVipGoodBaseService;
import org.jeecg.modules.putil.LoginUserUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * @Description: 浏览记录
 * @Author: jeecg-boot
 * @Date: 2025-02-19
 * @Version: V1.0
 */
@Slf4j
@Service
public class KrBrowseBaseServiceImpl extends ServiceImpl<KrBrowseBaseMapper, KrBrowseBase> implements IKrBrowseBaseService {

  @Resource
  private IKrUserTimeStatementService userTimeStatementService;

  @Resource
  private RedisUtil redisUtil;

  @Resource
  private LoginUserUtil loginUserUtil;

  @Resource
  @Lazy
  private IKrCurriculumVitaeBaseService curriculumVitaeBaseService;

  @Resource
  @Lazy
  private IKrHireBaseService hireBaseService;

  /**
   * 浏览简历信息
   *
   * @param contentId 被浏览的简历ID
   */
  @Transactional
  @Override
  public void visitContent(String contentId, String type, String msg) {
    String publisher = null;
    String userId = loginUserUtil.getLoginUser().getId();
    if (CommonConstant.VISIT_TYPE_ZW.equals(type)) {
      KrHireBase krHireBase = hireBaseService.getOptById(contentId).orElseThrow(() -> new JeecgBootException("您浏览的岗位不存在！"));
      publisher = krHireBase.getPublishUser();
    } else if (CommonConstant.VISIT_TYPE_JL.equals(type)) {
      KrCurriculumVitaeBase curriculumVitaeBase = curriculumVitaeBaseService.getOptById(contentId).orElseThrow(() -> new JeecgBootException("您浏览的简历不存在！"));
      publisher = curriculumVitaeBase.getPublishUser();
    }
    if (getByContentId(contentId, userId) != null) {
      return;
    }
    if (userId.equals(publisher)) {
      log.info(Strings.toColor("查看自己的信息不扣次数！", ConsoleColors.GREEN));
      saveBrowseBase(contentId, type, userId);
      return;
    }
    String date = Strings.valueOf(DateUtils.getLocalDate());
    String key = Strings.buildRedisKey(date, userId);
    //        判断是否已经浏览过
    // todo 不要再用魔法值，非消息类型的常量统一定义加注释描述！
    if (!redisUtil.hasKey(key)) {
      //            如果未浏览过，则存入，并且将value设为1,过期时间为24小时
      redisUtil.set(key, 1, 24 * 60 * 60);
    } else {
      //        如果已经浏览过，则获取浏览次数
      BigDecimal value = (BigDecimal) redisUtil.get(key);
      if (value.compareTo(new BigDecimal(10)) >= 0) {
        throw new JeecgBootException("您今天已经查看了10次，无法继续查看！");
      }
      redisUtil.incr(key, 1);
    }
    userTimeStatementService.modifyUserTime(userId, BigDecimal.ONE.negate(), msg);
    saveBrowseBase(contentId, type, userId);
  }

  /**
   * 保存一条浏览记录
   *
   * @param contentId 被保存的内容ID
   * @param type      浏览类型
   * @param userId    用户信息
   */
  @Override
  public void saveBrowseBase(String contentId, String type, String userId) {

    KrBrowseBase browseBase = new KrBrowseBase();
    browseBase.setContentId(contentId);
    browseBase.setType(type);
    browseBase.setUserId(userId);
    save(browseBase);
  }

  /**
   * 根据contentId查询浏览记录
   *
   * @param contentId 内容ID
   * @return 查询的结果数据
   */
  @Override
  public KrBrowseBase getByContentId(String contentId, String userId) {
    return getOne(new LambdaQueryWrapper<KrBrowseBase>().eq(KrBrowseBase::getContentId, contentId).eq(KrBrowseBase::getUserId, userId));
  }

  @Override
  public IPage<BrowseHisVO> myBrowse(Integer pageNo, Integer pageSize, String type) {
    IPage<BrowseHisVO> page = new Page<>(pageNo, pageSize);
    String id = loginUserUtil.getLoginUser().getId();
    if (CommonConstant.VISIT_TYPE_JL.equals(type)) {
      return this.baseMapper.selectCurrHis(page, id);
    } else if (CommonConstant.VISIT_TYPE_ZW.equals(type)) {
      return this.baseMapper.selectHireHis(page, id);
    }
    throw new JeecgBootException("错误的分类信息！");
  }
}
